<html>
<script>
//initiate global variabes
var changeval;
var storeprice;
var storeratio;
var avgprice;
var averagetype;
var repone;
var initavgprice;
var initavgindicator;
var initialratavg;
var ray;
var initial;
var stdev;
var mean;
var carlos;
var iterations;
var num;
var ccarlo;
var alpha;
var iavgratio;
var max;
var min;
var skew;
var kurtosis;
var stdevr;
var stdevp;
var stdevi;
var covar;
var steadystate;
	//create function to convert array to csv
	function convertArrayOfObjectsToCSV(args) {  
        var result, ctr, keys, columnDelimiter, lineDelimiter, data;

        data = args.data || null;
        if (data == null || !data.length) {
            return null;
        }

        columnDelimiter = args.columnDelimiter || ',';
        lineDelimiter = args.lineDelimiter || '\n';

        keys = Object.keys(data[0]);

        result = '';
        result += keys.join(columnDelimiter);
        result += lineDelimiter;

        data.forEach(function(item) {
            ctr = 0;
            keys.forEach(function(key) {
                if (ctr > 0) result += columnDelimiter;

                result += item[key];
                ctr++;
            });
            result += lineDelimiter;
        });

        return result;
    }
	
	//download changevl array
	function downloadCSVV(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: changeval
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
	
	//download price array
	function downloadCSVP(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: storeprice
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
	
	//download ratio array
	function downloadCSVR(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: storeratio
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
	
	//download avg price array
	function downloadCSVA(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: avgprice
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
	
	//download report 1 array
	function downloadCSV1(args) {  
        var data, filename, link;
        var csv = convertArrayOfObjectsToCSV({
            data: alpha
        });
        if (csv == null) return;

        filename = args.filename || 'export.csv';

        if (!csv.match(/^data:text\/csv/i)) {
            csv = 'data:text/csv;charset=utf-8,' + csv;
        }
        data = encodeURI(csv);

        link = document.createElement('a');
        link.setAttribute('href', data);
        link.setAttribute('download', filename);
        link.click();
    }
	
	
function admin(){
	//retrieve user inputted values
	stdev = parseFloat(document.getElementById("stdev").value);
	mean = parseFloat(document.getElementById("mean").value);
	carlos = parseFloat(document.getElementById("carlos").value);
	iterations = parseFloat(document.getElementById("iterations").value);
	change = parseFloat(document.getElementById("change").value);
	averagetype = document.getElementById("averagetype").value;
	//num is number of companies
	num = parseFloat(document.getElementById("firms").value);
	//create average price, changeval infrastructure
	avgprice = new Array(iterations);
	changeval = new Array(iterations);
	for (var i = 0; i < iterations; i++){
		avgprice[i] = new Array(carlos);
		changeval[i] = new Array(carlos);
	}
	//fill in avgprice and changeval with 0s
	for (var i = 0; i < iterations; i++){
		for (var p = 0; p < carlos; p++){
			avgprice[i][p] = 0;
			changeval[i][p] = 0;
		}
	}
	//create storeprice and storeratio infrastructure [i=iteration,t=firm]
	storeprice = new Array(carlos);
	storeratio = new Array(carlos);
	for (var i = 0; i < iterations; i++){
		storeratio[i] = new Array(num);
		storeprice[i] = new Array(num);
	}
	//create primary simulation array and duplicate to store initial values [company #][0=indicator,1=price]
	ray = new Array(num);
	initial = new Array(num);
	for (var i = 0; i < num; i++) {
		ray[i] = new Array(2);
	initial[i] = new Array(2);
	}

	//create arrays for report 1 and fill them in with zeros
	initialratavg = new Array(carlos);
	initavgprice = new Array(carlos);
	initavgindicator = new Array(carlos);
	covar = new Array(carlos);
	stdevi = new Array(carlos);
	below = new Array(carlos);
	max = new Array(carlos);
	min = new Array(carlos);
	skew = new Array(carlos);
	kurtosis = new Array(carlos);
	stdevr = new Array(carlos);
	stdevp = new Array(carlos);
	steadystate = new Array(carlos);
	for (var i = 0; i < carlos; i++){
		initialratavg[i] = 0;
		initavgprice[i] = 0;
		covar[i] = 0;
		initavgindicator[i] = 0;
		stdevi[i] = 0;
		below[i] = 0;
		max[i] = 0;
		min[i] = 0;
		skew[i] = 0;
		kurtosis[i] = 0;
		stdevr[i] = 0;
		stdevp[i] = 0;
		steadystate[i] = 0;
	}

	//create report 1 array 0=result 1=meaninitialratio 2=%below 3=lowir 4=highir 5=skew 6=kurtosis 7=stdev 8=correlation
	alpha = new Array(carlos);
	for (var u = 0; u < carlos; u++){
		alpha[u] = new Array(10);
	}
}

function createreports(i, m){
	//fill in change val for this iteration
	for(t = 0; t < num; t++){
		changeval[i][m] = changeval[i][m] + (ray[t][1] / initial[t][1] / num);
	}
		
	//fill in avgprice for this iteration
	for(t = 0; t < num; t++){
		avgprice[i][m] = avgprice[i][m] + (ray[t][1] / num);
	}
	avgprice[i][m] = avgprice[i][m] / initialpriceavg;
	//fill in storeprice for this iteration
	for(t = 0; t < num; t++){
		storeprice[i][t] = ray[t][1];
	}
		
	//fill in storeratio for this iteration
	for(t = 0; t < num; t++){
		storeratio[i][t] = ray[t][1] / ray[t][0];
	}
	
		for(w = 0; w < iterations; w++){
			if(avgprice[w][m] < 1.01 * avgprice[iterations - 1][m] && avgprice[w][m] > avgprice[iterations - 1][m] / 1.01){
				steadystate[m] = w;
				w = iterations;
			}
			
		}
}
		
//fill in report 1
function fillrep1(){
	for(var u=0;u<carlos;u++){
		alpha[u][0] = avgprice[iterations-1][u] / avgprice[0][u];
		alpha[u][1] = initialratavg[u];
		alpha[u][2] = below[u] / num;
		alpha[u][3] = min[u];
		alpha[u][4] = max[u];
		alpha[u][5] = skew[u];
		alpha[u][6] = kurtosis[u];
		alpha[u][7] = stdevr[u];
		alpha[u][8] = covar[u];
		alpha[u][9] = steadystate[u];
	}
}

//create values for report 1
function createreport1(i, m){
	//Calculate initial average price, indicator, and ratio
	for (var t = 0; t < num; t++){
			initavgprice[m] = initavgprice[m] + (initial[t][1] / num);
			initavgindicator[m] = initavgindicator[m] + (initial[t][0] / num);
			initialratavg[m] = initialratavg[m] + (initial[t][1] / initial[t][0] / num);
	}
	//initialize min and max
	min[m] = initial[0][1] / initial[0][0];
	max[m] = initial[0][1] / initial[0][0];
	//Calculate min, max, and percent below average
	for (var t = 0; t < num; t++){
		if(initial[t][1] / initial[t][0] < initialratavg[m]){
			below[m] = below[m] + 1;}
		if(initial[t][1] / initial[t][0] < min[m]){
			min[m] = initial[t][1] / initial[t][0];}
		if(initial[t][1] / initial[t][0] > max[m]){
			max[m] = initial[t][1] / initial[t][0];}
		}
		//Calculate covar, first part of Fisher-Pearson coefficient of skewness, kurtosis, stdevr, stdevp and stdevi
	for(var u = 0; u < num; u++){
		covar[m] = (initial[u][1] - initavgprice[m]) * (initial[u][0] - initavgindicator[m]) + covar[m];
		skew[m] = skew[m] + Math.pow(initial[u][1] / initial[u][0] - initialratavg[m],3);
		kurtosis[m] = kurtosis[m] + Math.pow(initial[u][1] / initial[u][0] - initialratavg[m],4);
		stdevr[m] = stdevr[m] + Math.pow(initial[u][1] / initial[u][0] - initialratavg[m],2);
		stdevp[m] = stdevp[m] + Math.pow(initial[u][1] - initavgprice[m],2);
		stdevi[m] = stdevi[m] + Math.pow(initial[u][0] - initavgindicator[m],2);
		}	
	//finish Standard Deviations, covar, kurtosis and skewness
	stdevr[m] = Math.pow(stdevr[m]/(num-1),.5);
	stdevp[m] = Math.pow(stdevp[m]/(num-1),.5);
	stdevi[m] = Math.pow(stdevi[m]/(num-1),.5);
	covar[m] = covar[m] / (num - 1) / stdevp[m] / stdevi[m];
	kurtosis[m] = kurtosis[m] / num / Math.pow(stdevr[m],4);
	skew[m] = skew[m] / num / Math.pow(stdevr[m],3);
}

function Calculate(){
admin();
//create monte carlo framework
for(var m = 0; m < carlos; m++){
	//fill in array [company #][0=indicator,1=price] use box-muller for indicators, uniform distro for multipliers
	for (var u = 0; u < num; u++) {
		var u1 = Math.random();
		var u2 = Math.random();
		var r = stdev * Math.sqrt(-2 * Math.log(u1));
		ray[u][0] = r * Math.cos(2 * Math.PI * u2) + mean;
		if(ray[u][0] < 1){
			ray[u][0] = 1;
		}
		ray[u][1] = ray[u][0] * Math.random();
	}
	//store initial values and sum initial prices
	initialpriceavg = 0;
	for(var u = 0; u < num; u++){
		initial[u][0] = ray[u][0];
		initial[u][1] = ray[u][1];
		initialpriceavg = initialpriceavg + (initial[u][1] / num);
		if(initial[u][1] == 0){
			initial[u][1] = 1;
		}
	}
	//iterate through simulation
	for(var i = 0; i < iterations; i++){
		//reset ratio
		ratio = 0;
		//calculate portfolio average ratio
		for(var r = 0; r < num; r++){
			if(averagetype == "Arithmetic"){
				ratio = (ray[r][1] / ray[r][0]) + ratio;}
			if(averagetype == "Harmonic"){
				ratio = 1 / (ray[r][1] / ray[r][0]) + ratio;}
		}
		if(averagetype == "Arithmetic"){
			ratio = ratio / num;
			//change market prices
			for(var p = 0; p < num; p++){
				//increase price if firm is undervalued compared to the ratio with the firm taken out
				if(ray[p][1] / ray[p][0] < (parseFloat(ratio)*num-ray[p][1] / ray[p][0])/(num-1)){
					ray[p][1] = ray[p][1] + change;
				}
				//decrease price if firm is overvalued compared to the ratio with the firm taken out
				else if(ray[p][1] / ray[p][0] > (parseFloat(ratio)*num-ray[p][1] / ray[p][0])/(num-1)){
					ray[p][1] = ray[p][1] - change;
				}
				//make 1 the lowest price
				if(ray[p][1] < 1){
					ray[p][1] = 1;
				}
			}
		}
		else if(averagetype == "Harmonic"){
			ratio = num / ratio;
			//change market prices
			for(var p = 0; p < num; p++){
				//increase price if firm is undervalued compared to the ratio with the firm taken out
					if(ray[p][1] / ray[p][0] < (num-1)/(1/(parseFloat(ratio)/num)-(ray[p][0]/ray[p][1]))){
					ray[p][1] = ray[p][1] + change;
					//ray[p][1] = ray[p][1] * (1 + change / 100);
				}
				//decrease price if firm is overvalued compared to the ratio with the firm taken out
				else if(ray[p][1] / ray[p][0] > (num-1)/(1/(parseFloat(ratio)/num)-(ray[p][0]/ray[p][1]))){
					ray[p][1] = ray[p][1] - change;
					//ray[p][1] = ray[p][1] / (1 + change / 100);
				}
				//make 1 the lowest price
				if(ray[p][1] < 1){
					ray[p][1] = 1;
				}
			}
		}
		createreports(i, m);
	}
	createreport1(i,m);
}
fillrep1();
}

</script>
<body>
<table>
<tr><td>Monte Carlo #:<input id="carlos" type=number value="10000"></td></tr>
<tr><td>Iterations: <input id="iterations" type=number value="350"></td></tr>
<tr><td># of Companies: <input id="firms" type=number value="10"></td></tr>
<tr><td>Amount Price Changes Each Iteration: <input id="change" type=number value="1"></td></tr>
<tr><td>Standard Deviation of Indicators: <input id="stdev" type=number value="100"></td></tr>
<tr><td>Mean of Indicators: <input id="mean" type=number value="500"></td></tr>
<tr><td>Type of Average Used: <select id="averagetype" value="Arithmethic">
  <option value="Arithmetic">Arithmetic</option>
  <option value="Harmonic">Harmonic</option>
</select></td></tr>


</table>
<input type="button" value="Calculate" onclick="Calculate()">
<br>
<a href='#' 
        onclick='downloadCSV1({ filename: "simple.csv" });'
    >Download Data</a>
		<p>Description of File</p>
	<p>0: Final Average Price<br>
1: Average Initial Multiple<br>
2: Share of Firm's with Multiples below the Average<br>
3: The lowest initial multiple<br>
4: The highest initial multiple<br>
5: The skew of the initial distribution of multiples<br>
6: The kurtosis of the initial distribution of multiples<br>
7: The standard deviation of the initial distribution of multiples<br>
8: The correlation between the initial indicators and initial prices<br>
9: Time to steady state<br></p>
<br>
<a href='#' 
        onclick='downloadCSVV({ filename: "changeval.csv" });'
    >Download CSV of Change in Value over Time</a>
<br>
<a href='#' 
        onclick='downloadCSVA({ filename: "storeavgprice.csv" });'
    >Download CSV of Change in Avg Price over Time</a>
<br>
<a href='#' 
        onclick='downloadCSVP({ filename: "storeprice.csv" });'
    >Download CSV of Individual Firm Price Over Time of last Carlo</a>
<br>
<a href='#' 
        onclick='downloadCSVR({ filename: "storeratio.csv" });'
    >Download CSV of Individual Firm Ratio Over Time of last Carlo</a>
</body>
</html>